package com.cat.gridChart;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;

/**
 * @author 曲大人的喵
 * @description https://leetcode.cn/problems/pond-sizes-lcci/
 * @create 2025/8/19 17:01
 * @since JDK17
 */

public class Solution03 {
    int n, m;
    int[][] dire = new int[][]{{1, 0}, {0, 1}, {1, -1}, {1, 1}};

    int dfs(int[][] grid, int x, int y) {
        int ans = 0;
        grid[x][y] = 1;
        for (int i = 0; i < 4; i++) {
            int nx = dire[i][0] + x, ny = dire[i][1] + y;
            if (nx < 0 || ny < 0 || nx == n || ny == m) {
                continue;
            }
            if (grid[nx][ny] == 0) {
                ans += 1 + dfs(grid, nx, ny);
            }
        }
        return ans;
    }

    public int[] pondSizes(int[][] land) {
        n = land.length;
        m = land[0].length;
        ArrayList<Integer> ans = new ArrayList<>();
        for (int i = 0; i < n; i++) {
            for (int j = 0; j < m; j++) {
                if (land[i][j] == 0) {  // 水域
                    ans.add(1 + dfs(land, i, j));
                }
            }
        }
        int[] res = new int[ans.size()];
        Collections.sort(ans);
        for (int i = 0; i < ans.size(); i++) {
            res[i] = ans.get(i);
        }
        return res;
    }
}
